﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Web;
using System.Web.UI;
using TB.Web.UI.WebControls;
using System.Xml;
using System.Drawing;

public partial class Main_Reports_Accounts_Profitandloss1 : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    AccountSettings ASetting = new AccountSettings();
    Double totalIncome = 0;
    Double totalExpenditure = 0;
    string strSql = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            hidFinyear.Value = Session["FINYEAR"].ToString();
            txtFromDate.Text = "01/04/" + Session["FINYEAR"].ToString();
            txtToDate.Text = "31/03/" + (int.Parse(Session["FINYEAR"].ToString()) + 1).ToString();
            PopulateTreeviewIncome(txtFromDate.Text, txtToDate.Text);
            PopulateTreeviewExpenditure(txtFromDate.Text, txtToDate.Text);
        }
    }

    private void PopulateTreeviewIncome(string strFromDate, string strToDate)
    {
        if (strFromDate != string.Empty && strToDate != string.Empty)
        {
            hidFromDate.Value = strFromDate;
            hidToDate.Value = strToDate;

            lblHeading.Text = "Profit & Loss A/c From " + Convert.ToDateTime(strFromDate).ToString("dd-MMM-yyyy") + " To " + Convert.ToDateTime(strToDate).ToString("dd-MMM-yyyy") + " .";
            string[] strArrDate = strFromDate.ToString().Split('/');
            strFromDate = strArrDate[1] + "/" + strArrDate[0] + "/" + strArrDate[2];
            strArrDate = strToDate.ToString().Split('/');
            strToDate = strArrDate[1] + "/" + strArrDate[0] + "/" + strArrDate[2];
            lblCompanyName.Text = Session["compname"].ToString();


            tvHierarchyViewIncome.Nodes.Clear();
            HierarchyTrees hierarchyTrees = new HierarchyTrees();
            HierarchyTrees.HTree objHTree = null;
            nodeDataDic = new Dictionary<string, TrailBalance>();
            string strIsFinyear = _IsFirstYear(Session["FINYEAR"].ToString());
            string strFinyear = Session["FINYEAR"].ToString();

            SqlParameter[] sparam ={
                                   new SqlParameter("@FROMDATE",strFromDate),
                                   new SqlParameter("@TODATE",strToDate),
                                   new SqlParameter("@ISFIRSTYEAR",strIsFinyear),
                                   new SqlParameter("@FINYEAR",strFinyear)
                               };
            SqlDataReader reader = DU.GetDataReaderUsingProcedure("USP_ACC_GetIncomeTree", sparam);

            while (reader.Read())
            {
                objHTree = new HierarchyTrees.HTree();
                string strLname = string.Empty;
                string strOpenBal = string.Empty;
                string strDebitBal = string.Empty;
                string strCreditBal = string.Empty;
                string strClosingBal = string.Empty;

                if (reader["GID"].ToString().Contains("L"))
                {
                    string lid = reader["GID"].ToString().Substring(1);
                    strLname = "<a href=\"#\" onclick=\"OpenMonthlySummary('" + lid + "','" + reader["GNAME"].ToString() + "','" + txtFromDate.Text + "','" + txtToDate.Text + "')\" runat=\"server\">" + reader["GNAME"].ToString() + "</a>";
                }
                else
                {
                    strLname = reader["GNAME"].ToString();
                    totalIncome = totalIncome + Convert.ToDouble(reader["ActBalance"].ToString());
                }
                if (reader["ACTBALANCE"].ToString() != string.Empty)
                {
                    strClosingBal = ASetting.GetCurrency(Convert.ToDouble(reader["ACTBALANCE"].ToString()));
                    
                }
                else
                {
                    strClosingBal = "&nbsp;";
                }
                objHTree.LevelDepth = int.Parse(reader["LEVEL_DEPTH"].ToString());
                objHTree.NodeID = reader["GID"].ToString();
                objHTree.UnderParent = reader["PID"].ToString();
                objHTree.NodeDescription = strLname;
                hierarchyTrees.Add(objHTree);
                nodeDataDic.Add(reader["GID"].ToString(), new TrailBalance(reader["GID"].ToString(), strLname, strOpenBal, strDebitBal, strCreditBal, strClosingBal));
            }
          
            foreach (HierarchyTrees.HTree hTree in hierarchyTrees)
            {
                HierarchyTrees.HTree parentNode = hierarchyTrees.Find(delegate(HierarchyTrees.HTree emp) { return emp.NodeID == hTree.UnderParent; });

                if (parentNode != null)
                {
                    foreach (TreeGridNode tn in tvHierarchyViewIncome.Nodes)
                    {
                        if (tn.Value == parentNode.NodeID.ToString())
                        {
                            TreeGridNode node = new TreeGridNode(hTree.NodeID.ToString());
                            node.DataItem = GetNodeData(node.Value);
                            tn.ChildNodes.Add(node);
                        }
                        if (tn.ChildNodes.Count > 0)
                        {
                            foreach (TreeGridNode ctn in tn.ChildNodes)
                            {
                                RecursiveChild(ctn, parentNode.NodeID.ToString(), hTree);
                            }
                        }
                    }
                }
                else
                {
                    TreeGridNode node = new TreeGridNode(hTree.NodeID.ToString());
                    node.DataItem = GetNodeData(node.Value);
                    tvHierarchyViewIncome.Nodes.Add(node);
                }
            }
            tvHierarchyViewIncome.ManualDataBind();
            //tvHierarchyView.RootNodeStyle.BackColor = Color.Blue;
            tvHierarchyViewIncome.ParentNodeStyle.BackColor = Color.Bisque;
            reader.Close();
         }
        
    }
    private void PopulateTreeviewExpenditure(string strFromDate, string strToDate)
    {
        if (strFromDate != string.Empty && strToDate != string.Empty)
        {
            string[] strArrDate = strFromDate.ToString().Split('/');
            strFromDate = strArrDate[1] + "/" + strArrDate[0] + "/" + strArrDate[2];
            strArrDate = strToDate.ToString().Split('/');
            strToDate = strArrDate[1] + "/" + strArrDate[0] + "/" + strArrDate[2];
        
            tvHierarchyViewExpenditure.Nodes.Clear();
            HierarchyTrees hierarchyTrees = new HierarchyTrees();
            HierarchyTrees.HTree objHTree = null;
            nodeDataDic = new Dictionary<string, TrailBalance>();
            string strIsFinyear = _IsFirstYear(Session["FINYEAR"].ToString());
            string strFinyear = Session["FINYEAR"].ToString();

            SqlParameter[] sparam ={
                                   new SqlParameter("@FROMDATE",strFromDate),
                                   new SqlParameter("@TODATE",strToDate),
                                   new SqlParameter("@ISFIRSTYEAR",strIsFinyear),
                                   new SqlParameter("@FINYEAR",strFinyear)
                               };
            SqlDataReader reader = DU.GetDataReaderUsingProcedure("USP_ACC_GetExpenditureTree", sparam);
            
            while (reader.Read())
            {
                objHTree = new HierarchyTrees.HTree();
                string strLname = string.Empty;
                string strOpenBal = string.Empty;
                string strDebitBal = string.Empty;
                string strCreditBal = string.Empty;
                string strClosingBal = string.Empty;

                if (reader["GID"].ToString().Contains("L"))
                {
                    string lid = reader["GID"].ToString().Substring(1);
                    strLname = "<a href=\"#\" onclick=\"OpenMonthlySummary('" + lid + "','" + reader["GNAME"].ToString() + "','" + txtFromDate.Text + "','" + txtToDate.Text + "')\" runat=\"server\">" + reader["GNAME"].ToString() + "</a>";
                }
                else
                {
                    strLname = reader["GNAME"].ToString();
                    totalExpenditure = totalExpenditure + Convert.ToDouble(reader["ActBalance"].ToString());
                }
                if (reader["ACTBALANCE"].ToString() != string.Empty)
                {
                    if (Convert.ToDouble(reader["ACTBALANCE"].ToString()) > 0)
                    {
                        strClosingBal = ASetting.GetCurrency(0 - Convert.ToDouble(reader["ACTBALANCE"].ToString()));

                    }
                    else
                    {
                        strClosingBal = ASetting.GetCurrency(Math.Abs(Convert.ToDouble(reader["ACTBALANCE"].ToString())));
                    }
                }
                else
                {
                    strClosingBal = "&nbsp;";
                }
                objHTree.LevelDepth = int.Parse(reader["LEVEL_DEPTH"].ToString());
                objHTree.NodeID = reader["GID"].ToString();
                objHTree.UnderParent = reader["PID"].ToString();
                objHTree.NodeDescription = strLname;
                hierarchyTrees.Add(objHTree);
                nodeDataDic.Add(reader["GID"].ToString(), new TrailBalance(reader["GID"].ToString(), strLname, strOpenBal, strDebitBal, strCreditBal, strClosingBal));
            }
           
            
            foreach (HierarchyTrees.HTree hTree in hierarchyTrees)
            {
                HierarchyTrees.HTree parentNode = hierarchyTrees.Find(delegate(HierarchyTrees.HTree emp) { return emp.NodeID == hTree.UnderParent; });

                if (parentNode != null)
                {
                    foreach (TreeGridNode tn in tvHierarchyViewExpenditure.Nodes)
                    {
                        if (tn.Value == parentNode.NodeID.ToString())
                        {
                            TreeGridNode node = new TreeGridNode(hTree.NodeID.ToString());
                            node.DataItem = GetNodeData(node.Value);
                            tn.ChildNodes.Add(node);
                        }
                        if (tn.ChildNodes.Count > 0)
                        {
                            foreach (TreeGridNode ctn in tn.ChildNodes)
                            {
                                RecursiveChild(ctn, parentNode.NodeID.ToString(), hTree);
                            }
                        }
                    }
                }
                else
                {
                    TreeGridNode node = new TreeGridNode(hTree.NodeID.ToString());
                    node.DataItem = GetNodeData(node.Value);
                    tvHierarchyViewExpenditure.Nodes.Add(node);
                }
            }
            tvHierarchyViewExpenditure.ManualDataBind();
            //tvHierarchyView.RootNodeStyle.BackColor = Color.Blue;
            tvHierarchyViewExpenditure.ParentNodeStyle.BackColor = Color.Bisque;
            reader.Close();

            Double finalTotal = totalExpenditure + totalIncome;

            if (finalTotal > 0)
            {

                lblNetProfit.Visible = true;
                lblNetLoss.Visible = false;
                lblTotalProfit.Text = ASetting.GetCurrency(finalTotal);
                //lblTotalLoss.Text = ASetting.GetCurrency(finalTotal);
                lblTotalExpenditure.Text = ASetting.GetCurrency(Math.Abs(finalTotal) + Math.Abs(totalExpenditure));
                lblTotalIncome.Text = ASetting.GetCurrency(Math.Abs(totalIncome));
            }
            else
            {
                lblNetLoss.Visible = true;
                lblNetProfit.Visible = false;
                lblTotalProfit.Text = ASetting.GetCurrency(Math.Abs(finalTotal));
                lblTotalExpenditure.Text = ASetting.GetCurrency(Math.Abs(totalExpenditure));
                lblTotalIncome.Text = ASetting.GetCurrency(Math.Abs(finalTotal) + Math.Abs(totalIncome));
            }
            if (finalTotal == 0)
            {
                lblTotalExpenditure.Text = totalExpenditure.ToString();
                lblTotalIncome.Text = totalIncome.ToString();
            }
        }
    }

    public void RecursiveChild(TreeGridNode tn, string searchValue, HierarchyTrees.HTree hTree)
    {
        if (tn.Value == searchValue)
        {
            TreeGridNode node = new TreeGridNode(hTree.NodeID.ToString());
            node.DataItem = GetNodeData(node.Value);
            tn.ChildNodes.Add(node);
        }
        if (tn.ChildNodes.Count > 0)
        {
            foreach (TreeGridNode ctn in tn.ChildNodes)
            {
                RecursiveChild(ctn, searchValue, hTree);
            }
        }
    }
    private string _IsFirstYear(string strFinYear)
    {
        string strIsFirstYear = string.Empty;
        strSql = "SELECT MIN(FINYEAR)AS FINYEAR FROM MAS_FINYEAR";
        DataTable DTMinFinyear = DU.getdata(strSql);
        if (DTMinFinyear.Rows.Count > 0)
        {
            if (DTMinFinyear.Rows[0]["FINYEAR"].ToString() != string.Empty)
            {
                if (Convert.ToInt32(DTMinFinyear.Rows[0]["FINYEAR"].ToString()) == Convert.ToInt32(strFinYear))
                {
                    strIsFirstYear = "1";
                }
                else
                {
                    strIsFirstYear = "0";
                }
            }
        }
        return strIsFirstYear;
    }
    protected void btnCangeDate_Click(object sender, EventArgs e)
    {
        PopulateTreeviewIncome(txtFromDate.Text, txtToDate.Text);
        PopulateTreeviewExpenditure(txtFromDate.Text, txtToDate.Text);
    }
    private static Dictionary<string, TrailBalance> nodeDataDic = null;
    public static TrailBalance GetNodeData(string nodeValue)
    {
        if (nodeDataDic.ContainsKey(nodeValue))
            return nodeDataDic[nodeValue];
        else
            return new TrailBalance("", "", "", "", "", "");
    }
   
    protected void tvHierarchyViewIncome_RowDataBound(object sender, TreeGridRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //e.Row.Cells[0].Attributes.Add("rowspan", "2");
            //e.Row.Cells[1].Attributes.Add("rowspan", "2");
            //e.Row.Cells[2].Attributes.Add("colspan", "2");
            //e.Row.Cells[2].Text = "Transactions";
            //e.Row.Cells.RemoveAt(3);
            //string strNewRow = "</td></tr><tr style=\"background-color:#E3EEE3; text-align:center; font-weight:bold;\"><td>Debit</td><td>Credit";
            //e.Row.Cells[3].Text = e.Row.Cells[3].Text + strNewRow;
            //e.Row.Cells[3].Attributes.Add("rowspan", "2");
        }

    }
    protected void tvHierarchyViewExpenditure_RowDataBound(object sender, TreeGridRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //e.Row.Cells[0].Attributes.Add("rowspan", "2");
            //e.Row.Cells[1].Attributes.Add("rowspan", "2");
            //e.Row.Cells[2].Attributes.Add("colspan", "2");
            //e.Row.Cells[2].Text = "Transactions";
            //e.Row.Cells.RemoveAt(3);
            //string strNewRow = "</td></tr><tr style=\"background-color:#E3EEE3; text-align:center; font-weight:bold;\"><td>Debit</td><td>Credit";
            //e.Row.Cells[3].Text = e.Row.Cells[3].Text + strNewRow;
            //e.Row.Cells[3].Attributes.Add("rowspan", "2");
        }
        
    }

}
public class HierarchyTrees : List<HierarchyTrees.HTree>
{
    public class HTree
    {
        private string m_NodeDescription;
        private string m_UnderParent;
        private int m_LevelDepth;
        private string m_NodeID;

        public string NodeID
        {
            get { return m_NodeID; }
            set { m_NodeID = value; }
        }

        public string NodeDescription
        {
            get { return m_NodeDescription; }
            set { m_NodeDescription = value; }
        }
        public string UnderParent
        {
            get { return m_UnderParent; }
            set { m_UnderParent = value; }
        }
        public int LevelDepth
        {
            get { return m_LevelDepth; }
            set { m_LevelDepth = value; }
        }
    }
}
public class TrailBalance
{
    public TrailBalance(string gid, string gname, string open, string debit, string credit, string closing)
    {
        this.gid = gid;
        this.gname = gname;
        this.open = open;
        this.debit = debit;
        this.credit = credit;
        this.closing = closing;
    }
    private string gid = string.Empty;
    private string gname = string.Empty;
    private string open = string.Empty;
    private string debit = string.Empty;
    private string credit = string.Empty;
    private string closing = string.Empty;


    public string GID
    {
        get { return this.gid; }
        set { this.gid = value; }
    }
    public string GName
    {
        get { return this.gname; }
        set { this.gname = value; }
    }
    public string OpenBal
    {
        get { return this.open; }
        set { this.open = value; }
    }
    public string Debit
    {
        get { return this.debit; }
        set { this.debit = value; }
    }
    public string Credit
    {
        get { return this.credit; }
        set { this.credit = value; }
    }
    public string ClosingBal
    {
        get { return this.closing; }
        set { this.closing = value; }
    }
}